package kr.hkit.powerjava.chapter24.work1;

import java.util.Comparator;
import java.util.Scanner;

public class ServiceStudent {
	// 시작(StudentDao 객체 생송후 load())
	// 메뉴보이기(prnMenu)
	// 종료(StudentDao.save)
	private StudentDaoo dao;
	private Scanner sc;

	public ServiceStudent() {
		dao = new StudentDaoo();
		sc = new Scanner(System.in);
		init();
	}

	public SericeStudent(StudentDaoo dao) {

		this.dao = dao;
		init();
	}

	private void init() {
		dao.loadFile();
		prnMenu();

	}

	private void prnMenu() {
		Student std=null;
		int res=0;
		do{
		System.out.println("1. 입렵\n2.삭제\n3.수정\n4.검색\n5.리스트보기\n6.종료\n");
		res = sc.nextInt();
		
		switch (res) {
			case 1:
				//학생정보입력
				std = inputStdInfo(true);//학번 ,성명,국어,영어,수학
				dao.insertItem(std);

				break;

			case 2:
				//리스트를 보여주고 삭제할 번호 입력
				dao.prnItemList(null);
				System.out.println("삭제할 학싱정보를 입력하시오.");
				std=inputStdInfo(false);
				dao.deleteItem(std);
				break;

			case 3://리스트를 보여주고 수정할 학생정보 입력받음
				dao.prnItemList(null);
				System.out.println("수정할 번호 입력");
				std=inputStdInfo(true);
				dao.updateItem(std);
				break;

			case 4:
				std = inputStdInfo(false);
				try {
					std=dao.searchItem(std);
					System.out.println(std);
				}catch (ArrayIndexOutOfBoundsException e) {
					System.out.println("학생정보없음");
				}

				break;

			case 5:
				prnSubMenu();
				break;

			case 6:
				dao.saveFile();
				sc.close();
				System.exit(0);
				break;

			default:
		}
			
		}while (res<=6);

	}

	private Student inputStdInfo(boolean gubun) {
		System.out.println("학번 성명");
		int num =sc.nextInt();
		String name =sc.next();
		if (gubun){
			System.out.println("국어 영어 수학");
			int kor = sc.nextInt();
			int eng = sc.nextInt();
			int math= sc.nextInt();
			return new Student(num,name,kor,eng,math);
		}else {
			return new Student(num, name);
		}
		
	}

	private void prnSubMenu() {
		System.out.println("1.이름순 2.성적순 3. 번호순");
		int res = sc.nextInt();
		switch (res) {
			case 1:
				dao.prnItemList(new Comparator<Student>() {
					
					@Override
					public int compare(Student o1, Student o2) {
						return o1.getStdName().hashCode()-o2.getStdName().hashCode();
					}
				});

				break;
				case 2:
					dao.prnItemList(new Comparator<Student>() {

						@Override
						public int compare(Student o1, Student o2) {
							
							return o1.totalScore()-o2.totalScore();
						}
					});
					break;
					case 3:
						dao.prnItemList(null);
						break;
						default:
							dao.prnItemList(null);

		}

	}

}
